"""
性能监控模块
功能：监控慢操作、统计性能指标
"""

import time
import logging
from functools import wraps

logger = logging.getLogger('email_system')


class PerformanceMonitor:
    """性能监控器"""
    
    def __init__(self):
        self.metrics = {
            'imap_connect': [],
            'imap_fetch': [],
            'db_query': [],
            'db_insert': [],
        }
    
    def record(self, operation, duration):
        """记录操作耗时"""
        if operation in self.metrics:
            self.metrics[operation].append(duration)
            
            # 只保留最近100条
            if len(self.metrics[operation]) > 100:
                self.metrics[operation] = self.metrics[operation][-100:]
    
    def get_stats(self, operation):
        """获取统计信息"""
        if operation not in self.metrics or not self.metrics[operation]:
            return None
        
        data = self.metrics[operation]
        return {
            'count': len(data),
            'avg': sum(data) / len(data),
            'min': min(data),
            'max': max(data),
        }


# 全局监控器
performance_monitor = PerformanceMonitor()


def monitor_performance(operation_name, threshold=5.0):
    """
    性能监控装饰器
    
    Args:
        operation_name: 操作名称
        threshold: 慢操作阈值（秒）
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            start_time = time.time()
            try:
                result = func(*args, **kwargs)
                return result
            finally:
                duration = time.time() - start_time
                performance_monitor.record(operation_name, duration)
                
                if duration > threshold:
                    logger.warning(
                        f"[性能警告] {func.__name__} 耗时 {duration:.2f}秒 (阈值: {threshold}秒)"
                    )
        
        return wrapper
    return decorator
